package com.hard;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lzscale.scalelib.misclib.Misc;
import com.lzscale.scalelib.misclib.Printer;
import com.seray.scalemisclib.R;
import com.tscale.scalelib.jniscale.JNIScale;

import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestActivity extends Activity {

    private static final String LINE_BREAK = "\r\n";
    ExecutorService printThread = Executors.newSingleThreadExecutor();
    private ScaleHandler mScaleHandler = new ScaleHandler(new WeakReference<>(this));
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);
    private Misc mMisc;
    private CardReadHelp mReadCardHelp;
    private JNIScale mScale;
    private Printer mPrinter;
    private TextView mKeyNameView, mCardIdView, mWeightView;
    private EditText mCardWriteName;
    private boolean isStop = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        mKeyNameView = findViewById(R.id.test_key_name);
        mCardIdView = findViewById(R.id.test_card_id);
        mCardWriteName= findViewById(R.id.write_card_name);
        mWeightView = findViewById(R.id.test_weight);
        mMisc = Misc.newInstance();
        mReadCardHelp = CardReadHelp.getSingleton();
        mPrinter = new Printer();
        mScale = JNIScale.getScale();
        timer();
    }

    private void timer() {
        Runnable timerRun = new Runnable() {
            @Override
            public void run() {
                if (!isStop)
                    mScaleHandler.sendEmptyMessage(1);
            }
        };
        timerThreads.scheduleAtFixedRate(timerRun, 1500, 50, TimeUnit.MILLISECONDS);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStop = true;
        if (mReadCardHelp != null)
            mReadCardHelp.cancelReadCard(null);
        timerThreads.shutdownNow();
        printThread.shutdownNow();
        mScaleHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        mMisc.beep();
        switch (keyCode) {
            case KeyEvent.KEYCODE_A:
                showKeyName("客户一");
                return true;
            case KeyEvent.KEYCODE_D:
                showKeyName("客户二");
                return true;
            case KeyEvent.KEYCODE_B:
                showKeyName("客户三");
                return true;
            case KeyEvent.KEYCODE_C:
                showKeyName("客户四");
                return true;
            case KeyEvent.KEYCODE_MENU:// 桌秤
            case KeyEvent.KEYCODE_MOVE_HOME:// 地秤
                showKeyName("菜单");
                return true;
            case KeyEvent.KEYCODE_F1:// 去皮
                showKeyName("去皮");
                return true;
            case KeyEvent.KEYCODE_F2:// 置零
                showKeyName("置零");
                return true;
            case KeyEvent.KEYCODE_NUM_LOCK: // 退格
                showKeyName("退格");
                return true;
            case KeyEvent.KEYCODE_DEL:// 语音
                showKeyName("语音");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_0:
                showKeyName("数字【0】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_1:
                showKeyName("数字【1】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_2:
                showKeyName("数字【2】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_3:
                showKeyName("数字【3】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_4:
                showKeyName("数字【4】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_5:
                showKeyName("数字【5】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_6:
                showKeyName("数字【6】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_7:
                showKeyName("数字【7】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_8:
                showKeyName("数字【8】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_9:
                showKeyName("数字【9】");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_DOT: // 一键清除
                showKeyName("清除");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_ADD:// 价格修改操作
                showKeyName("保存");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_ENTER: // 打印
                showKeyName("打印");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_SUBTRACT:// 商品
                showKeyName("商品");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_MULTIPLY: // 计件计重切换
                showKeyName("计件");
                return true;
            case KeyEvent.KEYCODE_NUMPAD_DIVIDE:// 取消
                showKeyName("取消");
                return true;
            case KeyEvent.KEYCODE_E: // 小数点
                showKeyName("小数点");
                return true;
            case KeyEvent.KEYCODE_F3: // 电源
                showKeyName("电源");
                return true;
            case KeyEvent.KEYCODE_BACK: // 返回
                showKeyName("返回");
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showKeyName(String name) {
        mKeyNameView.setText(String.format("%s-%s", "按键", name));
    }

    protected boolean isStable() {
        return mScale.getStabFlag();
    }

    public void onPrintTestClick(View view) {
        mMisc.beep();
        printThread.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    mPrinter.PrintGBKString(LINE_BREAK);
                    mPrinter.PrintGBKString(LINE_BREAK);
                    mPrinter.PrintGBKString("神锐计量" + LINE_BREAK);
                    mPrinter.expand(2, 2);
                    mPrinter.PrintGBKString("神锐计量" + LINE_BREAK);
                    mPrinter.expand(1, 1);
                    String sb = "神锐计量";
                    String str = getCenterStr("神锐计量", false);
                    mPrinter.PrintGBKString(str + LINE_BREAK);
                    mPrinter.expand(2, 2);
                    mPrinter.PrintGBKString(getCenterStr("神锐计量", true) + LINE_BREAK);
                    mPrinter.expand(1, 1);
                    mPrinter.printQRCode(sb, 6, Printer.CorrectionLevel.CORRECTION_L);
                    mPrinter.PrintGBKString(LINE_BREAK);
                    mPrinter.PrintGBKString(LINE_BREAK);
                    mPrinter.PrintGBKString(LINE_BREAK);
                    mPrinter.PrintGBKString(LINE_BREAK);
                } catch (Exception e) {
                    Log.e("Print", e.getMessage());
                }
            }
        });
    }

    String getCenterStr(String txt, boolean isBig) {
        if (isBig)
            return getCenterStr(txt, 16);
        return getCenterStr(txt, 32);
    }

    private String getCenterStr(String txt, int maxByteLen) {
        StringBuilder res = new StringBuilder();
        String spaceChar = " ";
        do {
            int len = getSingleByteCount(txt);
            if (len <= maxByteLen) {
                for (int i = 0; i < (maxByteLen - len) / 2; i++) {
                    res.insert(0, spaceChar);
                }
                res.append(txt);
                break;
            }
            String str = getStrByByteCount(txt, maxByteLen);
            res.append(str).append("\r\n");
            txt = txt.substring(str.length());
        } while (true);
        return res.toString();
    }

    private int getSingleByteCount(String txt) {
        char[] arr = txt.toCharArray();
        int i = 0, count = 0;
        for (; i < arr.length; i++) {
            if (arr[i] > 256)
                count += 2;
            else
                count++;
        }
        return count;
    }

    private String getStrByByteCount(String txt, int byteCount) {
        char[] arr = txt.toCharArray();
        int i = 0, count = 0;
        for (; i < arr.length; i++) {
            if (arr[i] > 256)
                count += 2;
            else
                count++;
            if (count == byteCount)
                return txt.substring(0, i + 1);
            else if (count > byteCount)
                return txt.substring(0, i);
        }
        return txt;
    }

    public void onMiscTestClick(View view) {
        mMisc.beepEx(100, 50, 3);
    }

    public void onBackClick(View view) {
        mMisc.beep();
        finish();
    }

    //读卡号
    public void onReadCardNumClick(View view) {
        mMisc.beep();
        mReadCardHelp.readCardNum(new ReturnValueCallback() {
            @Override
            public void run(ReturnValue result) {
                if (result != null) {
                    Message message = Message.obtain();
                    message.what = 0;
                    String msg;
                    Object tag = result.getTag();
                    if (tag != null)
                        msg = tag.toString();
                    else
                        msg = "未知错误";
                    message.obj = msg;
                    mScaleHandler.sendMessage(message);
                }
            }
        });
    }

    private byte[] writeData = new byte[16];

    //写入卡片内部数据块数据
    public void onWriteCardBlockClick(View view) {
        mMisc.beep();
        if(TextUtils.isEmpty(mCardWriteName.getText().toString())){
            Toast.makeText(getApplication(),"请输入名字",Toast.LENGTH_SHORT).show();
            return;
        }
        String cardIn =mCardWriteName.getText().toString();
        if(cardIn.length()<=4){
            for(int i=cardIn.length();i<4;i++){
                cardIn+="姚";
            }

        }

        String nameWriteStr = mReadCardHelp.toUnicode(cardIn).replace("\\u","");
        for (int i = 0; i < 16; i++) {
            writeData[i] = (byte) nameWriteStr.charAt(i);
        }

        mReadCardHelp.writeCardBlock(new ReturnValueCallback() {
            @Override
            public void run(ReturnValue result) {
                if (result != null) {
                    Message message = Message.obtain();
                    message.what = 0;
                    String msg;
                    Object tag = result.getTag();
                    if (tag != null)
                        msg = tag.toString();
                    else
                        msg = "未知错误";
                    message.obj = msg;
                    mScaleHandler.sendMessage(message);
                }
            }
        },writeData);
    }


    //读卡测试
    public void onReadCardTestClick(View view) {
        mMisc.beep();
        mReadCardHelp.readCardId(new ReturnValueCallback() {
            @Override
            public void run(ReturnValue result) {
                if (result != null) {
                    Message message = Message.obtain();
                    message.what = 0;
                    String msg;
                    Object tag = result.getTag();
                    if (tag != null)
                        msg = tag.toString();
                    else
                        msg = "未知错误";
                    message.obj = msg;
                    mScaleHandler.sendMessage(message);
                }
            }
        });
    }



    public void onOpenBoxTestClick(View view) {
        mMisc.beep();
        try {
            mMisc.openCashBoxAutoClose();
        } catch (Exception e) {
            Log.e("Misc", e.getMessage());
        }
    }

    private static class ScaleHandler extends Handler {

        WeakReference<TestActivity> mWeakReference;
        private CardReadHelp mReadCardHelp;

        ScaleHandler(WeakReference<TestActivity> weakReference) {
            this.mWeakReference = weakReference;
            this.mReadCardHelp=mReadCardHelp;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TestActivity activity = mWeakReference.get();
            if (activity != null && !activity.isFinishing()) {
                if (msg.what == 0) {
                    activity.mCardIdView.setText(msg.obj.toString());
                } else if (msg.what == 1) {
                    activity.mWeightView.setText(activity.mScale.getStringNet());
                }
            }
        }
    }
}
